package com.briup.estore.web.controller;

import com.briup.estore.Service.UserService;
import com.briup.estore.constant.BookStoreConstant;
import com.briup.estore.dto.UserLoginDTO;
import com.briup.estore.dto.UserMessageUpdateDTO;
import com.briup.estore.dto.UserRegisterDTO;
import com.briup.estore.dto.UserUpdatePasswordDTO;
import com.briup.estore.exception.BookStoreException;
import com.briup.estore.utils.JsonWebTokenUtils;
import com.briup.estore.vo.UserInfoVO;
import com.briup.estore.vo.UserLoginVO;
import com.briup.estore.web.response.Result;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@Api(tags = "用户模块")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) {//username= &
        //调用service 效验用户名和密码
        System.out.println("userLoginDTO = " + userLoginDTO);
        //登陆成功后 返回用户数据 dto参数 vo 相应类
        UserLoginVO userLoginVO = userService.login(userLoginDTO, BookStoreConstant.LOGIN_USER);
        return Result.success(userLoginVO);
    }

    @ApiOperation("当前用户信息")
    @GetMapping("getUserInfo")
    public Result getUserInfo(HttpServletRequest request) throws Exception {
        //从token中取出用户id，再去数据库查询
        Claims jwt = JsonWebTokenUtils.parseJWT(request.getHeader("token"));
        String userId = jwt.getSubject();
        //调用service 返回当前登陆者信息
        UserInfoVO user = userService.findById(userId);
        return Result.success(user);
    }


    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO) {
        userService.register(userRegisterDTO);
        return Result.success();
    }


    @ApiOperation("用户信息修改")
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody UserMessageUpdateDTO userMessageUpdateDTO) {
        UserInfoVO userInfoVO = userService.updateUser(userMessageUpdateDTO);
        return Result.success(userInfoVO);
    }


    @PutMapping("/updatePassword")
    @ApiOperation("密码修改")
    public  Result updatePassword(HttpServletRequest request, @RequestBody UserUpdatePasswordDTO userUpdatePasswordDTO){
        String userId = (String) request.getAttribute("userId");
        userService.updatePassword(Integer.parseInt(userId),userUpdatePasswordDTO.getOldPassword(),userUpdatePasswordDTO.getNewPassword());
        return  Result.success();
    }

}
